package com.yykj.weifenxiao.server.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.yykj.common.service.RedisService;
import com.yykj.common.util.HttpUtil;
import com.yykj.weifenxiao.server.config.WiFenXiaoConfig;
import com.yykj.weifenxiao.server.service.AccessTokenService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zeng
 * @Date 2022/3/9
 */
@Service
@AllArgsConstructor
@Slf4j
public class AccessTokenServiceImpl implements AccessTokenService {

    final RedisService redisService;

    @Override
    public String getAccessToken() {
        String accessToken = redisService.get(WiFenXiaoConfig.app_key);
        log.info("redis-accessToken:{}",accessToken);
        if (StrUtil.isEmpty(accessToken)) {
            //获取token

            Map<String, Object> map = new HashMap<>();
            map.put("shop_id", WiFenXiaoConfig.shop_id);
            map.put("app_key", WiFenXiaoConfig.app_key);
            map.put("secret", WiFenXiaoConfig.secret);
            try {
                String body = HttpUtil.get(WiFenXiaoConfig.baseUrl + "/token", map);
                JSONObject json = JSONUtil.parseObj(body);
                accessToken = json.getStr("access_token");
                log.info("获取微分销 accessToken {}",accessToken);
                Integer expires_in = Integer.parseInt(json.get("expires_in").toString());
                redisService.set(WiFenXiaoConfig.app_key, accessToken, expires_in - 600);
            } catch (UnirestException e) {
                e.printStackTrace();
            }
        }
        return accessToken;
    }
}
